<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.title" clearable prefix-icon="el-icon-search" placeholder="标题" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <!--        <el-input v-model="query.isup" clearable placeholder="置顶状态" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />-->
        <el-select v-model="query.isup" clearable placeholder="置顶状态" style="width: 185px;" class="filter-item" type="string" @keyup.enter.native="crud.toQuery">
          <el-option v-for="item in dict.top_status" :key="item.value" :value="item.value" :label="item.label" />
        </el-select>
        <el-select
          v-model="query.appType"
          clearable
          size="small"
          placeholder="系统"
          class="filter-item"
          style="width: 120px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in appTypes"
            :key="item.name"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
        <!--        <label class="el-form-item-label">创建者</label>
        <el-input v-model="query.createBy" clearable placeholder="创建者" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <label class="el-form-item-label">更新者</label>
        <el-input v-model="query.updateBy" clearable placeholder="更新者" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />-->
        <!--        <date-range-picker
          v-model="query.createTime"
          class="date-item"
        />-->
        <!--        <date-range-picker
          v-model="query.updateTime"
          class="date-item"
        />-->
        <rr-operation :crud="crud" />
      </div>
      <!--     如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crud-operation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="系统" prop="appTypeDatas" class="star">
            <el-select
              v-model="appTypeDatas"
              style="width: 370px;"
              multiple
              placeholder="请选择"
              @remove-tag="deleteTag"
              @change="changeAppType"
            >
              <el-option
                v-for="item in appTypes"
                :key="item.name"
                :label="item.name"
                :value="item.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <el-input v-model="form.content" :rows="8" type="textarea" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="置顶状态" prop="isup">
            <!--            <el-select v-model="form.isup">
              <el-option v-for="item in dict.top_status" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>-->
            <el-radio v-for="item in dict.top_status" :key="item.id" v-model="form.isup" :label="item.value === 'true'">{{ item.label }}</el-radio>
          </el-form-item>
          <!--          <el-form-item label="创建者">
            <el-input v-model="form.createBy" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="更新者">
            <el-input v-model="form.updateBy" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="创建日期">
            <el-input v-model="form.createTime" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="更新时间">
            <el-input v-model="form.updateTime" style="width: 370px;" />
          </el-form-item>-->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" height="calc(100vh - 310px)" stripe :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="appTypeName" label="系统" />
        <!--        <el-table-column prop="content" label="内容" :show-overflow-tooltip="true" />-->
        <el-table-column prop="isup" label="置顶状态">
          <template slot-scope="scope">
            {{ dict.label.top_status[scope.row.isup] }}
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="创建者" />
        <el-table-column prop="updateBy" label="更新者" />
        <el-table-column prop="createTime" width="140" label="创建日期" />
        <el-table-column prop="updateTime" label="更新时间" width="140" />
        <el-table-column prop="wxPublishTime" width="140" label="发布企微状态" />
        <el-table-column v-if="checkPer(['admin','announcement:edit','announcement:del'])" label="操作" width="320px" align="center" class-name="operate-column">
          <template slot-scope="scope">
            <ud-operation
              :data="scope.row"
              :permission="permission"
            >
              <div slot="left" style="display: inline-block">
                <el-button size="mini" type="text" icon="el-icon-position" :disabled="scope.row.isDeployed" :loading="scope.row.isSendingPlat" @click="handlePublish(scope.row)">发布平台</el-button>
                <el-button size="mini" type="text" icon="el-icon-chat-round" :loading="scope.row.isSendingWx" @click="handlePublishWx(scope.row)">发布企微</el-button>
              </div>

            </ud-operation>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudAnnouncement, { edit } from '@/api/information/announcement'
import CRUD, { presenter, header, form, crud } from '@brotherCrud/crud'
import rrOperation from '@brotherCrud/RR.operation'
import crudOperation from '@brotherCrud/CRUD.operation'
import udOperation from '@brotherCrud/UD.operation'
import pagination from '@brotherCrud/Pagination'
import eventBus from '../../../api/information/eventBus'
let userAppTypes = []
const defaultForm = { title: null, content: null, isup: null, createBy: null, updateBy: null, createTime: null, updateTime: null, anncId: null, appType: [], isDeployed: false }
export default {
  name: 'Announcement',
  components: { pagination, rrOperation, udOperation, crudOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['top_status'],
  cruds() {
    return CRUD({ title: '公告', url: 'api/announcement', idField: 'anncId', sort: 'annc_Id,desc', crudMethod: { ...crudAnnouncement }})
  },
  data() {
    return {
      appTypes: [
        { code: 1, 'name': '管理' },
        { code: 5, 'name': '工场' },
        { code: 6, 'name': 'HUB' },
        { code: 4, 'name': '设计库' }
      ],
      appTypeDatas: [],
      permission: {
        add: ['admin', 'announcement:add'],
        edit: ['admin', 'announcement:edit'],
        del: ['admin', 'announcement:del'],
        download: ['admin', 'announcement:download']
      },
      rules: {
        title: [
          { required: true, message: '标题不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '内容不能为空', trigger: 'blur' },
          { min: 1, max: 1000, message: '长度在 1 到 1000 个字符', trigger: 'blur' }
        ],
        isup: [
          { required: true, message: '置顶状态不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'title', display_name: '标题' },
        { key: 'isup', display_name: '置顶状态' },
        { key: 'createBy', display_name: '创建者' },
        { key: 'updateBy', display_name: '更新者' }
      ]
    }
  },
  watch: {
    /* 监听表格数据*/
    'crud.data': {
      handler: function(val) {
        eventBus.$emit('flag', true)
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    /*  钩子：在获取表格数据之前执行，false 则代表不获取数据*/
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    // 新增前将多选的值设置为空
    [CRUD.HOOK.beforeToAdd]() {
      this.appTypeDatas = []
    },
    // 初始化编辑时候的角色与系统
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.appTypeDatas = []
      userAppTypes = []
      const _this = this
      if (form.appType) {
        const appType = JSON.parse(form.appType)
        appType.forEach(function(appType, index) {
          _this.appTypeDatas.push(appType.code)
          const data = { code: appType.code, name: appType.name }
          userAppTypes.push(data)
        })
      }
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (this.appTypeDatas.length === 0) {
        this.$message({
          message: '系统不能为空',
          type: 'warning'
        })
        return false
      }
      crud.form.appType = userAppTypes
      return true
    },
    changeAppType(value) {
      userAppTypes = []
      const thiz = this
      value.forEach(function(data, index) {
        thiz.appTypes.map(item => {
          if (item.code === data) {
            const appType = { code: data, name: item.name }
            userAppTypes.push(appType)
          }
        })
      })
    },
    deleteTag(value) {
      userAppTypes.forEach(function(data, index) {
        if (data.code === value) {
          userAppTypes.splice(index, value)
        }
      })
    },
    handlePublishWx(row) {
      if (row.anncId) {
        this.$confirm(`确认发布企微?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$set(row, 'isSendingWx', true)
          const params = JSON.parse(JSON.stringify(row))
          params.renewWsPublished = true
          edit(params).then(rs => {
            this.crud.notify('发布成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
            this.$set(row, 'wxPublishTime', rs.wxPublishTime)
          }).finally(() => {
            this.$set(row, 'isSendingWx', false)
          })
        })
      }
    },
    // 发布
    handlePublish(row) {
      if (row.anncId) {
        this.$confirm(`确认发布公告?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$set(row, 'isSendingPlat', true)
          const params = row
          params.isDeployed = true
          edit(params).then(() => {
            this.crud.notify('发布成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
          }).finally(() => {
            this.$set(row, 'isSendingPlat', false)
          })
        })
      }
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .star>.el-form-item__label:before{
  content: "*";
  color: #ff4949;
  margin-right: 4px;
}
</style>
<style type="text/css" lang="scss">
  .operate-column{
    .uifix-ud-operation-btns {
        button{
          margin-right: 10px !important;
        }
    }
  }
</style>
